from urllib.request import urlopen
from html.parser import HTMLParser
import sys
import pokeparser
import pokeinfo

class pokedex(HTMLParser):
	count = 0
	startcount = 0
	info = []
	def __init__(self):
		super().__init__()
		self.in_table = self.in_tr = self.in_td = self.in_url = False
		self.pid = self.url = self.cname = self.jname = self.ename = ''

		self.parser = pokeparser.pokeparser()
		self.dextext = self.parser.gettext(self.parser.dex())
		self.f = open('text/dex.txt','a+',encoding='utf-8')
		self.u = open('url/dexurl.txt','a+',encoding='utf-8')
		with open('text/dex.txt',encoding='utf-8') as f:
			self.startcount = len(f.readlines()) * 3

	def handle_starttag(self, tag, attrs):
		attrs = dict(attrs)
		if tag == 'table':
			self.in_table = True
		elif tag=='tr' and self.in_table:
			self.in_tr = True
		# 获得宝可梦图鉴信息：
		elif tag=='a' and self.in_td and self.count % 3 == 0:
			self.in_url = True
			# 宝可梦地址：
			self.url = self.parser.combine(attrs.get('href', ''))
			# 中文名：
			self.cname = attrs.get('title', '')
			self.count += 1
			# 中文名打印在控制台，地址打印在文件中：
			if self.count > self.startcount:
				temp = sys.stdout
				sys.stdout = self.u
				print(self.url)
				self.u.flush()
				sys.stdout = temp
				print(self.cname)
		# 日文名：
		elif tag=='a' and self.in_td and self.count % 3 == 1:
			self.jname = attrs.get('title', '')
			self.count += 1
		# 英文名：
		elif tag=='a' and self.in_td and self.count % 3 == 2:
			self.ename = attrs.get('title', '')
			self.count += 1

	def handle_data(self, data):
		if data[0] == '#':
			self.in_td = True
	def handle_endtag(self, tag):
		if tag == 'a' and self.in_td and self.count % 3 == 0:
			self.in_td = False
			# 开始将宝可梦信息写入文件中:
			if self.count > self.startcount:
				# 读取每只宝可梦信息：
				p = pokeinfo.pokeinfo(self.url)
				p.feed(p.text)
				p.close()
				self.pid = '{num:03}'.format(num=self.count//3)
				self.info = [self.pid, self.cname, self.jname, self.ename, p.info[0], p.info[1],p.info[2], p.info[3], p.info[4], p.info[5]]
				# 将信息打印在控制台和文件中：
				temp = sys.stdout
				sys.stdout = self.f
				print(self.info)
				self.f.flush()
				sys.stdout = temp
				print(self.info)
		elif tag == 'table':
			self.in_table = self.in_tr = self.in_td = self.in_url = False
			self.count = 0

def writetxt():
	p = pokedex()
	p.feed(p.dextext)
	p.close()

if __name__ == "__main__":
	writetxt()